var singleStationList=null;
var singleMap=null;
var ifNeedGetAllForSingle=false;
var heatmapOverlay;
$(function(){
	getSingleType();
	getSingleStationCountTableData();

	singleMap = new BMap.Map("singleMap",{
		enableMapClick: false,
	   minZoom : 5,
		maxZoom : 18
	});

	singleMap.centerAndZoom(new BMap.Point(116.236044, 36.14466), 5);
	singleMap.enableScrollWheelZoom(); // 允许滚轮缩放
	heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20});
	singleMap.addOverlay(heatmapOverlay);
});

/**
 * 设置显示区域下拉框
 * @param data
 */
function getSingleType(){
	$.ajax({
		url : ctx+"/station/typeList",
		data : {},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(!showMsg(data)){
				return;
			}
			$('.single-heat  #stationType').combobox({
				valueField:'id',
				textField:'text',
				data:data.content,
				panelHeight:'auto'
			});
		}}

	);
}
/**
 * 站点数量统计情况
 * @param data
 */
function getSingleStationCountTableData(){
	$.ajax({
		url : ctx+"/station/countByAreaAndOrg",
		data : {},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(!showMsg(data)){
				return;
			}
			var org_level=data.org_level;
			var levelName="";
			if(org_level==0){
				levelName="省";
			}
			if(org_level==1){
				levelName="市";
			}
			if(org_level==2){
				levelName="县";
			}
			var counts=data.content;
			var txt="";
			for(var i=0;i<counts.length;i++){
				var c=counts[i];
				txt+='<tr><td>'+ c.areaName+'</td><td>'+ c.totalCount+'</td><td>'+ c.typeCount1+'</td><td>'+ c.typeCount2+'</td><td>'+ c.typeCount3+'</td><td>'+ c.typeCount4+'</td><td>'+ c.typeCount5+'</td></tr>'
			}
			$(".single-heat #station-count-table").html(txt);
		}}

	);
}

function showSingleAllStations(){
	if(ifNeedGetAllForSingle){
		hiddenMarker();
		$.ajax({
			url : ctx+"/station/query",
			data : {},
			dataType : 'json',
			type : 'get',
			success : function (data) {
				if(!showMsg(data)){
					return;
				}
				singleStationList=data.content.content;
				for(i=0;i<singleStationList.length;i++){
					var station=singleStationList[i];
					addSingleMarker(station,i);
				}
			}
		});
		ifNeedGetAllForSingle=false;
	}
}

function addSingleMarker(station,index){
	console.log("addSingleMarker");
	var marker = new BMap.Marker(new BMap.Point(station.latitude,station.longitude));
	var label = new BMap.Label(station.name,{offset:new BMap.Size(20,-10)});
	marker.setLabel(label);
	singleMap.addOverlay(marker);
	marker.setLabel(label);
	marker.addEventListener("click",function(){
		detailSingleStation(index);
	});
}
function hiddenMarker(){
	var allOverlay = singleMap.getOverlays();
	for (var i = 0; i < allOverlay.length ; i++){
		if(allOverlay[i].zc){
			if(allOverlay[i].zc.className.indexOf("BMap_Marker")>-1){
				singleMap.removeOverlay(allOverlay[i]);
			}
		}
	}
}
/**
 * 搜索
 */
function singleStationSearch(){
	var type=$("#stationType").val();
	var keyword=$("#keyword").val();
	var param={
		name:keyword,
		type: type,
		page: 0,
		size: 10
	}
	$.ajax({
		url : ctx+"/station/query",
		data : param,
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(!showMsg(data)){
				return;
			}
			ifNeedGetAllForSingle=true;
			singleStationList=data.content.content;

			hiddenMarker();
			$("#result_ul").html("");
			$(".search-result").hide();
			$(".search_detail").hide();

			for(i=0;i<singleStationList.length;i++){
				var station=singleStationList[i];
				var order=i+1;
				var txt='<li>'+
					'<a onclick="detailSingleStation('+i+');">'+
					'<span>'+order+'</span>'+
					'<span class="station-name">'+station.name+'</span>'+
					'<p>'+station.organName+' '+station.address+'</p>'+
					'</a>'+
					'</li>';

				$("#result_ul").append(txt);
				addSingleMarker(station,i);
			}
			$(".search_result").show();
			$(".search_result").find(".panel").show();
		}
	});
}
var showStationId=null;
function detailSingleStation(index){
	selectedId=null;
	var station = singleStationList[index];
	showStationId=station.id;
	singleMap.centerAndZoom(new BMap.Point(station.latitude,station.longitude),14);
	showSingleAllStations();
	getBaseDataForSingle(station.id);
	getEquipDataForSingle(station.id);
	getNowDataForSingle(station.id);
	//initNowDataTimerSingle();
	getHistoryDataForSingle(station.id,0);
	$(".search_result").hide();
	$(".search_detail").show();
	$(".search_detail").find(".panel-title").html(station.name);
}
function initNowDataTimerSingle(){
	//cleanNowDataTimer();
	NowDataTimer = window.setInterval(function(){
		refreshNowDataSingle();
	},60000);
}
function refreshNowDataSingle(){
	getNowDataForSingle(showStationId);
}
function getBaseDataForSingle(id){
	console.log("getBaseDataForSingle");
	$.ajax({
		url : ctx+"/station/detail",
		data : {id:id},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(data.result){
				var station=data.content;
				$(".single-heat #baseCode").html(station.code);
				$(".single-heat #baseName").html(station.name);
				$(".single-heat #baseType").html(station.type);
				$(".single-heat #baseDivision").html(station.cityName+station.districtName);
				$(".single-heat #baseOrgan").html(station.organName);
				$(".single-heat #baseAddress").html(station.address);
			}
		}
	})
}
function getEquipDataForSingle(id){
	console.log("getEquipDataForSingle");
	$(".single-heat #equip-tbody").html("");
	$.ajax({
		url : ctx+"/equip/query",
		data : {id:id,size:100},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(data.result){
				var equips=data.content.content;
				var txt="";
				for(var i=0;i<equips.length;i++){
					var equip=equips[i];
					var type=equip.type;
					if(!type){
						type="";
					}
					var status=equip.status;
					if(!status){
						status="";
					}
					txt+='<tr><td>'+equip.code+'</td><td>'+equip.name+'</td><td>'+type+'</td><td>'+status+'</td></tr>';
				}
				$("#equip-tbody").html(txt);
			}
		}
	})
}
function nowDateFormat(dateString){
	var arr1 = dateString.split(" ");
	var sdate = arr1[0].split('-');
	var result=sdate[0]+"年"+sdate[1]+"月"+sdate[2]+"日 "+arr1[1];
	return result;
}
function nowTimeFormat(dateString){
	var arr1 = dateString.split(" ");
	var sdate = arr1[1].split(':');
	var result=sdate[0]+":"+sdate[1];
	return result;
}
function getNowDataForSingle(id){
	console.log("getNowDataForSingle");
	$("#countTime").html("");
	$("#trainCount").html("");
	$("#now-tbody").html("");
	$.ajax({
		url : ctx+"/equipData/now?stationId="+id,
		data : {},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(data.result){
				var content=data.content;
				var timeStr=content.countTime;

				var timeShow=nowDateFormat(timeStr);

				$("#countTime").html(timeShow);
				$("#trainCount").html(content.trainCount);
				if(content.collectionTime==null){
					$("#now-tbody").html("<tr><td colspan='5'>暂无数据</td></tr>");
				}else{
					var time=nowTimeFormat(content.collectionTime);
					$("#now-tbody").html("<tr><td>"+content.collectionTime+"</td><td>"+content.plateNo+"</td><td>"+content.axleNumber+"</td><td>"+content.totalWeight+"</td><td>"+content.overrunWeight*100+"%</td></tr>");
				}
			}
		}
	})
}
function formatDatebox(value) {
	if (value == null || value == '') {
		return '';
	}
	var dt=convertDateFromString(value);
	return dt.format("hh:mm");
}

var selectedId;
var ifFirstPage=true;
function getHistoryDataForSingle(id,page){
	$("#history-tbody").html("");
	$.ajax({
		url : ctx+"/equipData/query?stationId="+id,
		data : {page:page,size:10},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(data.result){
				var num=data.content.totalPages;
				if(selectedId!=id){
					ifFirstPage=true;
					$("#PaginationSingle").pagination(num, {
						num_edge_entries: 1, //边缘页数
						num_display_entries: 4, //主体页数
						callback: pageselectCallbackForSingle,
						items_per_page: 1, //每页显示1项
						prev_text: "前一页",
						next_text: "后一页"
					});
				}
				selectedId=id;
				var histories=data.content.content;
				initHistoryDataForSingle(histories);
			}
		}
	})
}
function pageselectCallbackForSingle(page_index, jq){
	if(!ifFirstPage){
		getHistoryDataForSingle(selectedId,page_index);
	}
	ifFirstPage=false;
	return true;
}
function initHistoryDataForSingle(histories){
	if(histories==null||histories.length==0){
		$("#single-history-tbody").html("<tr><td colspan='5'>暂无数据</td></tr>");
	}else{
		var txt="";
		for(var i=0;i<histories.length;i++){
			var history=histories[i];
			var time=nowTimeFormat(history.collectionTime);
			var plateNo=history.plateNo;
			if(!plateNo){
				plateNo="";
			}
			var axleNumber=history.axleNumber;
			if(!axleNumber){
				axleNumber="";
			}
			var totalWeight=history.totalWeight;
			if(!totalWeight){
				totalWeight="";
			}
			var overrunWeight=history.overrunWeight;
			if(!overrunWeight){
				overrunWeight="";
			}else{
				overrunWeight=overrunWeight*100+"%";
			}
			txt+="<tr><td>"+history.collectionTime+"</td><td>"+plateNo+"</td><td>"+axleNumber+"</td><td>"+totalWeight+"</td><td>"+overrunWeight+"</td></tr>";
		}
		$("#single-history-tbody").html(txt);
	}
}

function showCount(){
	$(".count-panel .easyui-panel").show();
	$(".count-panel").find(".panel").show();
}
function showHeatMap(){
	$(".heat-map-panel .easyui-panel").show();
	$(".heat-map-panel").find(".panel").show();
}

$(document).ready(function(){
	//cleanNowDataTimer();
	if(HeatType==0){
		HeatType=1;
	}
	initRadio();
	initHeatTypeData(HeatType);
	$('.search_detail .easyui-panel').panel({
		onBeforeClose:function(){
			$(".search_detail").hide();
			return false;
		}
	});

	$(document).on('click', '.single-heat .heat-table input', function () {
		var type=$(this).val();
		if(type!=HeatType){
			initHeatTypeData(type);
		}
		HeatType=type;
	});
	$(document).on('click', '.single-heat .heat-map-panel span:contains("多图模式")', function () {
		$('ul li span:contains("多图热力图")').parent().click();
	});
});
function initRadio(){
	if(HeatType==1){
		$(".heat-table .weight-type").click();
	}
	if(HeatType==2){
		$(".heat-table .overrun-type").click();
	}
	if(HeatType==3){
		$(".heat-table .train-type").click();
	}
}

function setGradient(){
	var gradient = {};
	var colors = document.querySelectorAll("input[type='color']");
	colors = [].slice.call(colors,0);
	colors.forEach(function(ele){
		gradient[ele.getAttribute("data-key")] = ele.value;
	});
	heatmapOverlay.setOptions({"gradient":gradient});
}
//判断浏览区是否支持canvas
function isSupportCanvas(){
	var elem = document.createElement('canvas');
	return !!(elem.getContext && elem.getContext('2d'));
}
function initHeatTypeData(type){
	console.log("initHeatTypeData");
	var url="";
	if(type==1){
		url=ctx+"/equipData/count?type=weight"
	}
	if(type==2){
		url=ctx+"/equipData/count?type=overrun"
	}
	if(type==3){
		url=ctx+"/equipData/count?type=train"
	}

	$.ajax({
		url : url,
		data : {},
		dataType : 'json',
		type : 'get',
		success : function (data) {
			if(data.result){
				var stations=data.content;
				var points=new Array();
				var max=0;
				for(var i=0;i<stations.length;i++){
					var station=stations[i];
					var totalValue=station.totalValue;
					if(max<totalValue){
						max=totalValue;
					}
					var point={
						"lng":station.latitude,
						"lat":station.longitude,
						"count":station.totalValue
					}
					points.push(point);
				}
				heatmapOverlay.setDataSet({data:points,max:max});
			}
		}
	})

}
